package com.thingple.uhf;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;

import java.util.Date;

/**
 * 长时间打开设备时使用.<br/>
 * 控制心跳,APP异常退出后设备可以关闭
 * Created by lism on 2017/7/26.
 */
public class DeviceSession {

    private static final String INVENTORY_HEATBEAT_PERMISSION = "com.thingple.tag.permission.heartbeat";
    private static final String INVENTORY_HEATBEAT_ACTION = "com.thingple.tag.heartbeat";

    private static DeviceSession session;

    public Context context;

    private Handler handler;

    private boolean running = false;

    private boolean stopped = false;

    public static DeviceSession newInstance(Context context) {
        if (session != null) {
            session.stop();
        }
        session = new DeviceSession(context);

        return session;
    }

    public static DeviceSession currentInstance() {
        return session;
    }

    private DeviceSession(Context context) {
        this.context = context;
        this.handler = new Handler();
    }

    /**
     * 开始heatbeat操作
     */
    void start() {
        if (stopped) {
            throw new RuntimeException("Session has been stopped");
        }
        if (running) {
            Log.d("DeviceSession", "Session is already running");
            return;
        }
        running = true;
        heartbeat();
    }

    /**
     * 告诉session停止heartbeat操作
     */
    public void stop() {
        Log.d("DeviceSession", "关闭Session");
        if (!running) {
            Log.d("DeviceSession", "Session 并未启动");
        }
        running = false;
        stopped = true;
    }

    private void heartbeat() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {

                Intent intent = new Intent(INVENTORY_HEATBEAT_ACTION);
                intent.putExtra("time", new Date().getTime());
                Log.d(getClass().getName(), "发送广播Action:" + INVENTORY_HEATBEAT_ACTION + "\tPermission:" + INVENTORY_HEATBEAT_PERMISSION);
                context.sendBroadcast(intent, INVENTORY_HEATBEAT_PERMISSION);
                //context.sendBroadcast(intent);

                // delay
                if (!stopped) {
                    handler.postDelayed(this, 500);
                } else {
                    // 释放引用
                    context = null;
                    handler = null;
                }
            }
        };

        handler.postDelayed(runnable, 500);
    }
}
